package com.mdd.common.dynamicdatasource.config;

import com.mdd.common.dynamicdatasource.context.SpringContextUtils;
import com.mdd.common.dynamicdatasource.entity.TenantInfo;
import com.mdd.common.dynamicdatasource.service.ITenantInfoService;
import com.mdd.common.util.TimeUtils;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态数据源初始化
 */
@Slf4j
//@Configuration
public class DynamicDataSourceInit {

    //@Resource
    private ITenantInfoService tenantInfoService;

    @Bean
    public void initDataSource() {
        log.info("======初始化动态数据源=====");
        DynamicDataSource dynamicDataSource = (DynamicDataSource) SpringContextUtils.getBean("dynamicDataSource");
        HikariDataSource master = (HikariDataSource) SpringContextUtils.getBean("master");
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("master", master);

        List<TenantInfo> tenantList = tenantInfoService.getAllList();
        for (TenantInfo info : tenantList) {
            log.info("appId:{},name:{},active:{},endDate:{}", info.getTenantId(), info.getTenantName(), info.getIsActive(), TimeUtils.dateToStr(info.getEndTime(), TimeUtils.SECOND));
            HikariDataSource dataSource = new HikariDataSource();
            dataSource.setDriverClassName(info.getPropDriver());
            dataSource.setJdbcUrl(info.getPropUrl());
            dataSource.setUsername(info.getPropUsername());
            dataSource.setPassword(info.getPropPassword());
            dataSource.setDataSourceProperties(master.getDataSourceProperties());
            dataSourceMap.put(info.getTenantId(), dataSource);
        }
        // 设置数据源
        dynamicDataSource.setDataSources(dataSourceMap);
        /**
         * 必须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效
         */
        dynamicDataSource.afterPropertiesSet();
    }
}
